<template>
    <!-- 地址信息 -->
    <van-contact-card type="edit" :tel="address.mobile" :name="address.consignee" @click="toAddrssPages"
        v-if="Object.values(address).length > 0" />
    <van-contact-card type="add" @click="toAddrssPages" v-else />
    <!-- 商品信息 -->
    <van-card :key="confirmslist.proid" :price="confirmslist.total" :num="confirmslist.nums"
      :thumb="confirmslist.product.thumbs_text">
      <template #title>
          <h3>{{ confirmslist.product.name }}</h3>
      </template>
      <template #desc>
          <div v-if="confirmslist.attrs">
              <van-tag v-for="items in confirmslist.attrs" type="primary" size="large" style="margin-right: 10px;">{{
                  items.value }}</van-tag>
          </div>
          <div v-else>
              <van-tag type="danger" size="large" style="margin-right: 10px;">无商品规格</van-tag>
          </div>
          <h4>单价: {{ confirmslist.price }}</h4>
      </template>
  </van-card>
  
    <!-- 支付方式 -->
    <van-field v-model="payName" is-link readonly label="支付方式" placeholder="选择支付方式" @click="showPicker = true" />
    <van-popup v-model:show="showPicker" round position="bottom">
        <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
    </van-popup>
  
    <!-- 优惠券单元格 -->
    <van-coupon-cell :coupons="couponlist" :chosen-coupon="chosenCoupon" @click="showList = true" />
    <!-- 优惠券列表 -->
    <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
        <van-coupon-list :coupons="couponlist" :chosen-coupon="chosenCoupon" @change="onChange"
            :show-exchange-bar="false" />
    </van-popup>
  
    <!-- 订单备注 -->
    <van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" maxlength="120" placeholder="请输入订单备注"
        show-word-limit />
  
    <!-- 提交订单 -->
    <van-submit-bar :price="total" button-text="确认支付" @submit="onSubmit" />
  
  </template>
  <script setup>
import { ref } from 'vue';
import product from '../../api/product/product';

  const route = useRoute()
  const { proxy } = getCurrentInstance()
  const LoginUser = reactive(proxy.$cookies.get('LoginUser'));
  const cartids = ref(proxy.$route.query.cartids ?? 0)
  const address = ref(proxy.$cookies.get('address') ?? {})
  const proid = ref(proxy.$route.query.proid ?? 0)
  const cartlist = ref([])
  const remark = ref('')
  const columns = [
    { text: '余额', value: 'money' },
    { text: '微信', value: 'wx' },
    { text: '支付宝', value: 'zfb' }
  ];
  
  //优惠券
  const payName = ref('');
  const showPicker = ref(false);
  const pay = ref('')
  
  const onConfirm = ({ selectedOptions }) => {
    showPicker.value = false;
    payName.value = selectedOptions[0].text;
    pay.value = selectedOptions[0].value;
  };
  
  const couponlist = ref([]);
  const showList = ref(false);
  const chosenCoupon = ref(-1);
  
  const onChange = (index) => {
    showList.value = false;
    chosenCoupon.value = index;
  };
  
  
  onBeforeMount(() => {
    getShopData()
    if (JSON.stringify(address.value) == '{}') {
        getAddressSelected()
    }
    getCouponData()
  })
  const info = ref([])
  const SkuShow = ref(false)
  const sku = ref({})
  const properties = ref([])
  const goods = ref({})
  const orderlist=ref({})
  const name=ref([])
  const price=ref()
  name.value=route.query.names.split(',')
  const nums=route.query.nums
  const attrs=route.query.attrs
  const confirmslist=ref({
    total:0,
    nums:0,
    product:{},
    attrs:[],
    price:0
  })
  const getShopData = async () => {
    let result = await Api.ProductConfirms({
        proid: proid.value,
        busid: LoginUser.id ?? 0,
        attrs: attrs.toString(),
        nums: nums
    })
    if (result.code == 1) {
        console.log(result.data)
        confirmslist.value=result.data

          if (confirmslist.value.attrs) {
            confirmslist.value.attrs = JSON.parse(confirmslist.value.attrs)
          }
    }
  }
  
  const getAddressSelected = async () => {
    let result = await Api.AddressOrder({
        busid: LoginUser.id
    })

    if (result.code == 1) {
        address.value = result.data
        proxy.$cookies.set("address", {
            id: result.data.id,
            consignee: result.data.consignee,
            mobile: result.data.mobile
        });
    }
  }
  
  const getCouponData = async () => {
    let result = await Api.CouponOrder({
        busid: LoginUser.id
    })
  
    if (result.code == 1) {
        result.data.forEach((item) => {
            couponlist.value.push({
                id: item.id,
                condition: '正在活动中',
                value: 0,
                name: item.coupon.title,
                startAt: item.coupon.createtimes,
                endAt: item.coupon.endtime,
                valueDesc: parseFloat(item.coupon.rate) * 100,
                unitDesc: '折',
                rate: item.coupon.rate
            })
        })
    }
  }
  
  
  
  const toAddrssPages = () => {
    proxy.$router.push({
        path: '/business/address/index',
        query: {
            action: 'order'
        }
    })
  }
//   console.log(info)
  // 计算
  const total = computed(() => {
    let num = 0
    num = parseFloat(confirmslist.value.total);
    if (chosenCoupon.value != '-1') {
        let totals = parseFloat(confirmslist.value.total);
        let rate = parseFloat(couponlist.value[chosenCoupon.value].rate)
        // 打折之后的价格
        num = (totals * rate).toFixed(2)
        // 优惠券金额
        let price = (totals - num) * 100
        couponlist.value[chosenCoupon.value].value = price
    }
  
    return num * 100
  })
  
  const onSubmit = async () => {
  
    if(JSON.stringify(address.value) == '{}')
    {
        error('请选择收货地址');
        return false;
    }
  
    if (!pay.value) {
        error('请选择支付方式');
        return false;
    }
  
    let data = {
        busid: LoginUser.id,
        businessaddrid: address.value.id,
        amount: total.value / 100,
        remark: remark.value,
        pay: pay.value,
        couponid: chosenCoupon.value != '-1' ? couponlist.value[chosenCoupon.value].id : 0,
        nums: confirmslist.value.nums,
        attrs:confirmslist.value.attrs,
        price: confirmslist.value.price,
        total: confirmslist.value.total,
        proid: confirmslist.value.product.id,
        product: confirmslist.value.product,
    }
  console.log(data)
    let result = await Api.OrderAdds(data)
    if (result.code == 1) {
        success({
            message: result.msg,
            onClose: () => {
                proxy.$router.push('/business/index')
            }
        });
    } else {
        error(result.msg);
    }
  }
  
  </script>
  <style scoped>
  /* 组件穿透样式写法 */
  :deep .van-field__control:read-only {
    text-align: right;
  }
  </style>